package com.stars.easyms.logger.support.logback.redefine;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.util.ContextSelectorStaticBinder;
import ch.qos.logback.core.CoreConstants;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.status.StatusUtil;
import ch.qos.logback.core.util.StatusPrinter;
import com.stars.easyms.logger.support.logback.EasyMsLogbackLoggerContext;
import com.stars.easyms.logger.support.logback.util.EasyMsLogbackContextInitializer;
import org.slf4j.ILoggerFactory;
import org.slf4j.helpers.Util;
import org.slf4j.spi.LoggerFactoryBinder;

/**
 * <p>className: EasyMsStaticLoggerBinder</p>
 * <p>description: StaticLoggerBinder重写</p>
 *
 * @author guoguifang
 * @date 2019-08-15 23:25
 * @since 1.3.0
 */
public class EasyMsStaticLoggerBinder implements LoggerFactoryBinder {

    public static String REQUESTED_API_VERSION = "1.7.16";

    static final String NULL_CS_URL = CoreConstants.CODES_URL + "#null_CS";

    private static EasyMsStaticLoggerBinder SINGLETON = new EasyMsStaticLoggerBinder();

    private static Object KEY = new Object();

    static {
        SINGLETON.init();
    }

    private boolean initialized = false;
    private LoggerContext defaultLoggerContext = new LoggerContext();
    private final ContextSelectorStaticBinder contextSelectorBinder = ContextSelectorStaticBinder.getSingleton();

    private EasyMsStaticLoggerBinder() {
        defaultLoggerContext.setName(CoreConstants.DEFAULT_CONTEXT_NAME);
    }

    public static EasyMsStaticLoggerBinder getSingleton() {
        return SINGLETON;
    }

    static void reset() {
        SINGLETON = new EasyMsStaticLoggerBinder();
        SINGLETON.init();
    }

    void init() {
        try {
            new EasyMsLogbackContextInitializer(defaultLoggerContext).autoConfig();
            if (!StatusUtil.contextHasStatusListener(defaultLoggerContext)) {
                StatusPrinter.printInCaseOfErrorsOrWarnings(defaultLoggerContext);
            }
            contextSelectorBinder.init(defaultLoggerContext, KEY);
            initialized = true;
        } catch (JoranException je) {
            Util.report("Failed to auto configure default logger context", je);
        } catch (Exception t) {
            Util.report("Failed to instantiate [" + LoggerContext.class.getName() + "]", t);
        }
    }

    @Override
    public ILoggerFactory getLoggerFactory() {
        if (!initialized) {
            reset();
            if (!initialized) {
                return defaultLoggerContext;
            }
        }
        return new EasyMsLogbackLoggerContext(defaultLoggerContext);
    }

    @Override
    public String getLoggerFactoryClassStr() {
        return contextSelectorBinder.getClass().getName();
    }

}